package com.example.demo.component;


import com.example.demo.config.RedisConfig;
import com.example.demo.controller.FriendController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.ConcurrentModificationException;
import java.util.concurrent.ConcurrentHashMap;

//通过这个类来记录当前用户在线的状态(维护一下 userId 和 WebSocketSession 之间的映射)
@Component
public class OnlineUserManager {


    //后期改成使用redis


    @Autowired
    private static Logger log = LoggerFactory.getLogger(OnlineUserManager.class);

    @Autowired
    private RedisConfig redisConfig;

    private ConcurrentHashMap<Integer, WebSocketSession> sessions = new ConcurrentHashMap<>();

    //1.用户上线,哈希表插入键值对
    public void online(Integer userId,WebSocketSession session)
    {
        if(sessions.get(userId) != null && redisConfig.getStringKeyValue(userId) != session.getId()) //针对多开
        {
            //说明用户已经在线了,不能重复登陆.不记录这个映射关系
            log.warn("用户ID为:" + userId, "用户已登录,登录失败");
            return;
        }
        sessions.put(userId,session);

        //redis
        System.out.println("key-value存储到redis中");
        Boolean isSaveSuccess = redisConfig.setStringKeyValue(userId,session);
        if(isSaveSuccess == false)
        {
            log.warn("userId 和 WebSocketSession 存储到redis失败");
            return;
        }

        log.info("用户ID："+userId+"的用户上线");
    }

    //2.用户下线,删掉映射关系
    public void offline(Integer userId,WebSocketSession session)
    {
        WebSocketSession existSession = sessions.get(userId);

        //redis
        String jsonWebSocketSession = redisConfig.getStringKeyValue(userId);

        if(existSession == session)
        {
            //如果两个 session 是一个session 才可以删除,也是防止多开
            sessions.remove(userId);
            Boolean ret = redisConfig.deleteStringKetValue(userId);
            if(ret == false)
            {
                log.warn("键值对删除失败");
                return;
            }
            log.info("用户Id为:" + userId + "的用户下线");
        }
    }

    //根据 userId 获取到 WebSocketSession
    public WebSocketSession getSession(Integer userId)
    {
        return sessions.get(userId);
    }

}
